<?php
/*******************************************************************************
 * $Date:: Jan 12, 2011 9:55:21 AM                                              $
 * $Revision:                                                                  $
 * $Author:: Tuan Duong                                                        $
 * $Comment::                                                                  $
 ******************************************************************************/ 
/**
 * Description here...
 * 
 * @package Lua
 * @subpackage Builder
 * @author Tuan Duong <bacduong[at]gmail[dot]com>
 * @version 
 */

class Lua_Test_Builder_Factory
{
    private $builders = array();
    private $sequences = array();

    public final function create($name, array $extras = array())
    {
        $builder = $this->getBuilder($name);
        return $builder->create($extras);
    }

    /**
     * @param string $name
     * @return Lua_Test_Builder_Abstract
     */
    public function getBuilder($name)
    {
        if (!isset($this->builders[$name])) {
            $className = "Lua_Test_Builder_$name";

            if (!class_exists($className, true)) {
                throw new Lua_Test_Exception("Builder '$name' not found");
            }
            $classRef = new ReflectionClass($className);
            if (!$classRef->isSubclassOf('Lua_Test_Builder_Abstract') || !$classRef->isInstantiable()) {
                throw new Lua_Test_Exception("Invalid builder '$name'");
            }

            $builder = new $className();
            /* @var $builder Lua_Test_Builder_Abstract */
            $builder->setFactory($this);
            
            $this->builders[$name] = $builder;
        }

        return $this->builders[$name];
    }

    /**
     * @param string $name
     * @return string
     */
    public function getSequence($name = null)
    {
        $name = '' . $name;
        if (isset($this->sequences[$name])) {
            $this->sequences[$name]++;
        } else {
            $this->sequences[$name] = 1;
        }
        return $this->sequences[$name];
    }

    private static $instance;
    
    public static function getInstance()
    {
        if (self::$instance == null) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    /**
     * Create new row in datababase
     * @param string $name
     * @param array $extra
     * @return Lua_Bean_Abstract
     */
    public static function factory($name, array $extra = array())
    {
        return self::getInstance()->create($name, $extra);
    }
    
}